package com.lzx.adx.report.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Hex;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.text.MessageFormat;

@Slf4j
public class HwSecureUtil {

    public static final String Charsets_UTF_8="utf-8";

    /**
     * 计算请求头中的 Authorization
     *
     * @param body 消息体 json
     * @param key 秘钥
     * @return Authorization 鉴权头
     */
    public static String buildAuthorizationHeader(String body, String key) {
// 请求头 header 中的 Authorization 格式
        final String authorizationFormat = "Digest validTime=\"{0}\", response=\"{1}\"";
        String authorization = null;
        try {
            byte[] keyBytes = key.getBytes(Charsets_UTF_8);
            byte[] bodyBytes = body.getBytes(Charsets_UTF_8);
            Mac mac = Mac.getInstance("HmacSHA256");
            SecretKey secretKey = new SecretKeySpec(keyBytes, "HmacSHA256");
            mac.init(secretKey);
            byte[] signatureBytes = mac.doFinal(bodyBytes);
            final String timestamp = String.valueOf(System.currentTimeMillis());
            final String signature = (signatureBytes == null) ? null : Hex.encodeHexString(signatureBytes);
            authorization = MessageFormat.format(authorizationFormat, timestamp, signature);
        } catch (Exception e) {
            log.error("build Authorization Header failed！");
            log.error("build Authorization Header failed！ 错误为{}",e);
        }
       log.info("generate Authorization Header: " + authorization);
        return authorization;
    }
}
